<script setup lang="ts">
import { computed, reactive, ref, shallowRef, watch } from 'vue';
import type { Model } from 'echarts';
import { useCopyProperties, useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
import { enableStatusOptions } from '@/constants/business';
import { fetchAddDept, fetchGetDeptTree, fetchUpdateDept } from '@/service/api';
import { convertToTreeSelectOptions } from '@/utils/common';

defineOptions({
  name: 'DeptOperateDrawer'
});

// 操作类型
export type OperateType = NaiveUI.TableOperateType | 'addChild';

interface Props {
  /** the type of operation */
  operateType: OperateType;
  /** the edit row data */
  rowData?: Api.System.Dept | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<OperateType, string> = {
    add: '新增部门',
    edit: '编辑部门',
    addChild: '新增子部门'
  };
  return titles[props.operateType];
});

const model: Api.System.DeptEditModel = reactive(createDefaultModel());

function createDefaultModel(): Api.System.DeptEditModel {
  return {
    id: null,
    parentId: 0,
    deptName: '',
    treeSort: 10,
    status: '0'
  };
}

type RuleKey = Extract<keyof Model, 'remarks'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  deptName: defaultRequiredRule,
  treeSort: defaultRequiredRule,
  status: defaultRequiredRule
};

const isEdit = computed(() => props.operateType === 'edit');

async function handleInitModel() {
  Object.assign(model, createDefaultModel());
  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, useCopyProperties(props.rowData, 'id', 'parentId', 'deptName', 'treeSort', 'status'));
  } else if (props.operateType === 'addChild' && props.rowData) {
    model.parentId = props.rowData.id!;
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();
  let success: boolean = false;
  if (props.operateType === 'add') {
    const { error } = await fetchAddDept(model);
    if (!error) success = true;
  } else if (props.operateType === 'edit') {
    const { error } = await fetchUpdateDept(model);
    if (!error) success = true;
  }

  if (success) {
    window.$message?.success($t('common.updateSuccess'));
    closeDrawer();
    emit('submitted');
  }
}

// const deptTreeSelectTion = ref<Array<TreeSelectOption>>([]);

const deptTree = shallowRef<Api.Common.TreeRecord[]>([]);
// 获取部门树
async function getDeptTree() {
  const { error, data } = await fetchGetDeptTree();

  if (!error) {
    deptTree.value = data;
  }
}

watch(visible, () => {
  if (visible.value) {
    // 加载部门数据
    getDeptTree();
    handleInitModel();
    restoreValidation();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" display-directive="show" :width="360">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem label="上级部门" path="parentId">
          <NTreeSelect v-model:value="model.parentId" :options="deptTree" key-field="id" />
        </NFormItem>

        <NFormItem label="部门名称" path="deptName">
          <NInput v-model:value="model.deptName" placeholder="请输入部门名称" />
        </NFormItem>

        <NFormItem label="排序" path="treeSort">
          <NInputNumber v-model:value="model.treeSort" :step="5" placeholder="请选择排序" />
        </NFormItem>

        <NFormItem :label="$t('page.manage.role.roleStatus')" path="status">
          <NRadioGroup v-model:value="model.status">
            <NRadio v-for="item in enableStatusOptions" :key="item.value" :value="item.value" :label="$t(item.label)" />
          </NRadioGroup>
        </NFormItem>
      </NForm>
      <NSpace v-if="isEdit">
        <!--
 <NButton @click="openMenuAuthModal">{{ $t('page.manage.role.menuAuth') }}</NButton>
        <MenuAuthModal v-model:visible="menuAuthVisible" :role-id="roleId" />
        <NButton @click="openButtonAuthModal">{{ $t('page.manage.role.buttonAuth') }}</NButton>
        <ButtonAuthModal v-model:visible="buttonAuthVisible" :role-id="roleId" /> 
-->
      </NSpace>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
